<template>
  <el-card shadow="never"
           :body-style="{ padding: '12px' }">
    <el-tabs v-model="activeName"
             @tab-click="handleClick">
      <el-tab-pane :label="$t('billing.aLaCarteUsage')"
                   name="first"
                   v-if="aLaCarteTable.length > 0"
                   v-loading="loading">
        <el-table :data="aLaCarteTable"
                  v-if="activeName==='first'"
                  style="width: 100%">
          <el-table-column prop="name"
                           :label="$t('billing.assets')">
          </el-table-column>
          <el-table-column prop="quantity"
                           :label="$t('billing.quantity')">
          </el-table-column>

          <el-table-column prop="nextBilling"
                           :label="$t('billing.nextBilling')">
            <template slot-scope="scope">{{scope.row.nextBilling | UTCFormat}}</template>
          </el-table-column>
          <el-table-column prop="onboarding"
                           label="Onboarding Services">
            <template slot-scope="scope">
              <span v-if="!scope.row.payStatus">-</span>
              <span v-else-if="scope.row.name === 'Attendance'">Onboarding(Available)</span>
              <span v-else>{{scope.row.onboarding | onboardingFilter}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="amount" v-if="youBundles" :label="$t('billing.amount')">
            <template slot-scope="scope">
              <span>${{scope.row.amount / 100}}</span>
            </template>
          </el-table-column>
          <el-table-column label="Action">
            <template slot-scope="scope">
              <div class="action" v-if="scope.row.name !== 'Miscellaneous Fee' && scope.row.name !== 'BrightGauge Price Matching'">
<!--                <a-la-carte-pay v-if="dataFrom!=='tenant'" :detail="scope.row"></a-la-carte-pay>-->
                <el-tooltip content="Add on"
                            v-if="dataFrom!=='tenant'"
                            placement="top"
                            :open-delay="1000">
                  <button class="icon"
                          @click="jump">
                    <i class="cuifont icon_cart_alt"></i>
                  </button>
                </el-tooltip>
                <el-tooltip content="Renew"
                            placement="top"
                            :open-delay="1000">
                  <button :disabled="scope.row.payStatus || aLaCarteDisable"
                          class="icon"
                          @click="activationSubscription(scope.row)">
                    <i class="cuifont icon_undo"></i>
                  </button>
                </el-tooltip>
                <el-tooltip content="Cancel"
                            placement="top"
                            :open-delay="1000">
                  <button :disabled="!scope.row.payStatus"
                          class="icon"
                          @click="cancelSubscription(scope.row)">
                    <i class="cuifont icon_x"></i>
                  </button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane :label="$t('billing.bundlesUsage')"
                   name="second"
                   v-if="youBundles && youBundles.name !== 'A LA CARTE'"
                   v-loading="loading">
        <el-table :data="bundlesTable"
                  v-if="activeName==='second'"
                  style="width: 100%">
          <el-table-column prop="name"
                           :label="$t('billing.assets')">
          </el-table-column>
          <el-table-column :label="$t('billing.quantity')">
            <template slot-scope="scope">
              <span v-if="scope.row.name === 'Users'">{{countUser}}</span>
              <span v-else-if="scope.row.name === 'Attendance Only User'">{{scope.row.usersLimit}}</span>
              <span v-else-if="scope.row.name === 'Onboarding Service'">{{scope.row.onboarding }}</span>
              <span v-else-if="checkHtml(scope.row.threshold.label)">
                {{scope.row.threshold.value === 'Infinity' ? 'Included' : scope.row.threshold.value}}
              </span>
              <span v-else-if="scope.row.type === 13">-</span>
              <span v-else-if="scope.row.name === 'Bot Usage' && typeof scope.row.threshold.value === 'string'">{{scope.row.threshold.value}} Bots/User</span>
              <span v-else>{{scope.row.threshold.label ? scope.row.threshold.label : scope.row.threshold.value === 'Infinity' ? 'Included' : scope.row.threshold.value}}</span>
            </template>
          </el-table-column>

          <el-table-column prop="nextBilling"
                           :label="$t('billing.nextBilling')">
            <template slot-scope="scope">{{scope.row.nextBilling |UTCFormat}}</template>
          </el-table-column>

          <el-table-column :label="$t('label.action')"
                           v-if="dataFrom!=='tenant' && $hasPermission('sys:billing:action')">
            <template slot-scope="scope">
<!--              <el-tooltip content="Add More User"-->
<!--                          placement="top"-->
<!--                          :open-delay="1000">-->
<!--                <button class="icon"-->
<!--                        :disabled="!bundlesData.payStatus"-->
<!--                        v-if="scope.row.name === 'Users'"-->
<!--                        @click="addUser">-->
<!--                  <i class="cuifont icon_user_plus"></i>-->
<!--                </button>-->
<!--              </el-tooltip>-->
              <el-tooltip content="Setting"
                          placement="top"
                          :open-delay="1000">
                <button class="icon"
                        :disabled="!bundlesData.payStatus"
                        v-if="scope.row.name === 'Business Intelligence' && youBundles.name === 'STARTUP' "
                        @click="showBiSetting">
                  <i class="cuifont icon_settings"></i>
                </button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <moreUser :visible.sync="addUserVisible"
              :user="countUser"
              :attendanceOnlyNumber="attendanceOnlyNumber"
              :attendanceOnlyInfo="attendanceOnlyInfo"
              :bundlesData="bundlesData"></moreUser>
    <bi-package-setting :youBundles="youBundles"
                        :visible.sync="showBi"
                        :intelligenceNumber="intelligenceNumber"></bi-package-setting>
  </el-card>
</template>

<script>
import moreUser from './moreUser'
import biPackageSetting from './biPackageSetting'
import aLaCartePay from './aLaCartePay'
import { stringRemoveSpaceEqual } from '@/utils'
import config from '@/utils/config'

export default {
  name: 'useTable',
  props: ['customer', 'youBundles', 'timestamp', 'dataFrom'],
  inject: {
    _tenantCode: {
      default: () => {
        return function () { }
      }
    }
  },
  components: {
    moreUser,
    biPackageSetting,
    aLaCartePay
  },
  computed: {
    tenantCode () {
      return this._tenantCode()
    },
    aLaCarteDisable () {
      return !!(this.bundlesData && stringRemoveSpaceEqual(this.bundlesData.name, 'A la Carte') && !this.bundlesData.payStatus)
    }
  },
  data () {
    return {
      loading: false,
      addUserVisible: false,
      showBi: false,
      activeName: 'second',
      countUser: 0,
      aLaCarteTable: [],
      bundlesTable: [],
      bundlesData: {},
      intelligenceNumber: null,
      attendanceOnlyInfo: {},
      attendanceOnlyNumber: null
    }
  },
  watch: {
    timestamp () {
      this.getData()
    }
  },
  filters: {
    onboardingFilter (val) {
      if (!val) {
        return '-'
      }
      const isExpired = new Date(val) <= Date.now()
      if (isExpired) {
        return 'Onboarding (Expired)'
      }
      return 'Onboarding (Available)'
    }
  },
  methods: {
    handleClick (tab, event) {
    },
    checkHtml (htmlStr) {
      const reg = /<[^>]+>/g
      return reg.test(htmlStr)
    },
    async getData () {
      this.aLaCarteTable = []
      this.bundlesTable = []
      this.activeName = 'second'
      if (!this.customer.id) {
        this.$emit('update:youBundles', false)
        this.$emit('update:aLaCarte', false)
        return false
      }
      this.loading = true
      const { subList } = this.$interface.pay
      try {
        // const { data } = await subList({ customerId: this.customer.id })
        const tenantCode = this.tenantCode || this.$store.state.user.tenantCode
        const { data } = await subList({ tenantCode })
        if (data.code !== 0) {
          this.$message.error(data.msg)
        } else {
          let bundlesTable = ''
          let aLaCarteTable = ''
          if (data.data) {
            bundlesTable = this._.find(data.data, { type: 0 })
            if (bundlesTable && bundlesTable.sysPaywalls) {
              // const showKey = ['Users', 'Bots', 'Business Intelligence', 'Sync Integrations', 'Process Automation', 'NextTicket Manager', 'Attendance Manager']
              bundlesTable.sysPaywalls = this._.filter(bundlesTable.sysPaywalls, (item) => {
                if (item.name === 'Sync Integrations') {
                  item.name = 'Business Intelligence'
                  this.intelligenceNumber = item.threshold.value
                }
                item.nextBilling = bundlesTable.nextBilling
                // return showKey.includes(item.name)
                return item.type !== 99
              })
              const attendanceOnlyIndex = this._.findIndex(bundlesTable.sysPaywalls, { name: 'attendanceOnly' })
              const attendanceOnly = this._.find(bundlesTable.sysPaywalls, { name: 'attendanceOnly' })
              if (attendanceOnly) {
                attendanceOnly.name = 'Attendance Only User'
                this.attendanceOnlyNumber = attendanceOnly ? attendanceOnly.usersLimit : 0
                this.attendanceOnlyInfo = attendanceOnly
                bundlesTable.sysPaywalls.splice(attendanceOnlyIndex, 1)
                if (this.attendanceOnlyNumber) {
                  bundlesTable.sysPaywalls.unshift(attendanceOnly)
                }
              }
              const userIndex = this._.findIndex(bundlesTable.sysPaywalls, { name: 'Users' })
              const user = this._.find(bundlesTable.sysPaywalls, { name: 'Users' })
              if (user) {
                bundlesTable.sysPaywalls.splice(userIndex, 1)
                bundlesTable.sysPaywalls.unshift(user)
              }
              this.countUser = bundlesTable.usersLimit
              // this.countUser = await this.getUserNumber(bundlesTable.appId)

              if (bundlesTable.name === 'STARTUP') {
                let onboarding
                const isExpired = new Date(bundlesTable.onboarding) <= Date.now()
                if (!bundlesTable.onboarding) {
                  onboarding = '-'
                } else if (isExpired) {
                  onboarding = 'Expired'
                } else {
                  onboarding = 'Available'
                }

                bundlesTable.sysPaywalls.push({
                  name: 'Onboarding Service',
                  onboarding
                })
              }
              if (bundlesTable.name === 'PROFESSIONAL') {
                bundlesTable.sysPaywalls.push({
                  name: 'Onboarding Service',
                  onboarding: 'Included'
                })
              }
            }

            this.bundlesTable = bundlesTable ? bundlesTable.sysPaywalls : []

            this.bundlesData = bundlesTable
            aLaCarteTable = this._.filter(data.data, (o) => { return o.type !== 0 })
            this.aLaCarteTable = aLaCarteTable.map(item => {
              const obj = this._.find(item.subscriptionItem, { item_type: 'addon', item_price_id: item.itemId }) || {}
              item.quantity = item.usersLimit ? item.usersLimit : (obj.quantity || '-')
              if (item.name.includes('Bot Usage')) {
                item.quantity = item.usersLimit * (item.botValue || 1)
              }
              return item
            })
            if (this.aLaCarteTable.length > 0) {
              this.activeName = 'first'
            }
          }
          this.$emit('update:youBundles', bundlesTable)
          this.$emit('update:aLaCarte', aLaCarteTable)
          this.loading = false
        }
      } catch (e) {
        console.log(e)
        this.loading = false
      }
    },
    async cancelSubscription (row) {
      if (this.dataFrom === 'tenant') {
        this.$msgbox({
          title: this.$t('prompt.title'),
          message: this.$t('billing.cancelTip'),
          confirmButtonText: this.$t('billing.cancelNow'),
          cancelButtonText: this.$t('billing.dismiss'),
          showCancelButton: true,
          type: 'warning'
        }).then(async () => {
          const { updateSubscription, paywallDelete } = this.$interface.pay
          let addonsDtoList = []
          let chargesDTOS = []
          row.subscriptionItem.map(item => {
            if (row.itemId !== item.item_price_id) {
              if (item.item_type === 'addon') {
                addonsDtoList.push({
                  quantity: item.quantity,
                  id: item.item_price_id
                })
              }
              if (item.item_type === 'charge') {
                chargesDTOS.push({
                  quantity: item.quantity,
                  id: item.item_price_id,
                  servicePeriodDays: item.service_period_days
                })
              }
            }
          })
          const params = {
            customerId: this.customer.id,
            planId: this._.find(row.subscriptionItem, {item_type: 'plan'}).item_price_id,
            subscriptionId: row.subscriptionId,
            addonsDtoList: addonsDtoList,
            chargesDTOS: chargesDTOS,
            replaceItemsList: true
          }
          try {
            await updateSubscription(params)
            await paywallDelete({
              appId: row.appId,
              subscriptionId: row.subscriptionId
            })
            this.$message.success(this.$t('billing.cancelSuccess'))
            await this.getData()
          } catch (e) {
            this.$message.error('error')
            console.log(e)
          }
          // const { cancelSubscription } = this.$interface.pay
          // try {
          //   const { data } = await cancelSubscription({ subscriptionId: row.subscriptionId })
          //   if (data.code !== 0) {
          //     this.$message.error(data.msg)
          //   } else {
          //     this.$message.success(this.$t('billing.cancelSuccess'))
          //     await this.getData()
          //   }
          // } catch (e) {
          //   console.log(e)
          // }
        }).catch(() => { })
      } else {
        const url = this.$router.resolve({ name: 'feedback', query: { FormTitle: 'Cancel Subscription', RoleEamil: this.$store.state.user.email, tenantCode: this.$store.state.user.tenantCode } })
        window.open(url.href, '_blank')
      }
    },
    async activationSubscription (row) {
      this.$msgbox({
        title: this.$t('prompt.title'),
        message: this.$t('billing.renewTip'),
        confirmButtonText: this.$t('billing.renewNow'),
        cancelButtonText: this.$t('billing.dismiss'),
        showCancelButton: true,
        type: 'warning'
      }).then(async () => {
        const { activationSubscription } = this.$interface.pay
        try {
          const { data } = await activationSubscription({ subscriptionId: row.subscriptionId })
          if (data.code !== 0) {
            this.$message.error(data.msg)
          } else {
            this.$message.success(this.$t('billing.renewSuccess'))
            await this.getData()
          }
        } catch (e) {
          console.log(e)
        }
      }).catch(() => { })
    },
    jump () {
      this.$router.push({
        path: '/paywallBuy'
      })
    },
    async getUserNumber (appId) {
      const { payUserInfo, paywallFreeAccountList } = this.$interface.reports
      let { data } = await payUserInfo({ appId })
      const userTotal = data.data.total

      const { data: res } = await paywallFreeAccountList({ queryStr: '' })
      const whiteList = this._.filter(res.data, item => {
        return item.type !== 2 && item.tenantCode === this.$store.state.user.tenantCode
      })
      return Number(userTotal) + whiteList.length
    },
    addUser () {
      this.addUserVisible = true
    },
    showBiSetting () {
      this.showBi = true
    },
    addALaCarte (row) {}
  }
}
</script>

<style scoped>
.action {
  display: flex;
}
.icon {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f2f4f8;
  border-radius: 2px 2px 2px 2px;
  margin-right: 8px;
  cursor: pointer;
  border: none;
}
</style>
